package nix.demo2.dao;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import nix.demo2.domain.User;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class UserDaoImpl implements UserDao {

	private String path = "d:/users.xml";
	
	@Override
	public User findByUsername(String username) {

		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(path);
			Element element = (Element) document
					.selectSingleNode("//user[@username='" + username + "']");
			if (element == null) {
				return null;
			}
			User user = new User();
			user.setUsername(element.attributeValue("username"));
			user.setPassword(element.attributeValue("password"));

			return user;
		} catch (DocumentException e) {
			throw new RuntimeException();
		}
	}

	@Override	
	public void add(User user) {

		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(path);
			Element root = document.getRootElement();
			Element element = root.addElement("user");
			element.addAttribute("username", user.getUsername());
			element.addAttribute("password", user.getPassword());

			// OutputFormat format = OutputFormat.createPrettyPrint();
			OutputFormat format = new OutputFormat("\t", true);
			format.setTrimText(true);
			XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(path),"utf-8"), format);
			writer.write(document);
			writer.close();
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}
}
